﻿using Microsoft.AspNetCore.Http.HttpResults;
using System.Xml.Linq;
using Microsoft.EntityFrameworkCore;
using Rbac.Api.Data;
using Rbac.Api.Dto;
using Rbac.Api.Entity;
using Rbac.Api.ServiceInterface;

namespace Rbac.Api.Service;

public class PermissionService : IPermissionService
{
    private readonly UserDbContext _dbContext;


    public PermissionService(UserDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public async Task<IEnumerable<PermissionDto>> GetAllPermissionsAsync()
    {
        return await _dbContext.Permissions
            .Select(p => new PermissionDto
            {
                Id = p.Id,
                Name = p.Name,
                Description = p.Description,
                CreatedAt = p.CreatedAt,
                UpdatedAt = p.UpdatedAt
            })
            .ToListAsync();
    }

    public async Task<PermissionDto> GetPermissionByIdAsync(int id)
    {
        var permission = await _dbContext.Permissions.FindAsync(id);

        if (permission == null)
        {
            return null;
        }


        return new PermissionDto
        {
            Id = permission.Id,
            Name = permission.Name,
            Description = permission.Description,
            CreatedAt = permission.CreatedAt,
            UpdatedAt = permission.UpdatedAt
        };

    }

    public async Task<PermissionDto> CreatePermissionAsync(CreatePermissionDto createDto)
    {
        var permission = new Entity.Permission
        {
            Name = createDto.Name,
            Description = createDto.Description,
            CreatedAt = DateTime.UtcNow
        };

        await _dbContext.Permissions.AddAsync(permission);

        await _dbContext.SaveChangesAsync();

        return new PermissionDto
        {
            Id = permission.Id,
            Name = permission.Name,
            Description = permission.Description,
            CreatedAt = permission.CreatedAt,
            UpdatedAt = permission.UpdatedAt
        };
    }

    public async Task<bool> UpdatePermissionAsync(UpdatePermissionDto updateDto)
    {
        var existPermission = await _dbContext.Permissions.FindAsync(updateDto.Id);

        if (existPermission == null)
        {
            return false;
        }


        existPermission.Name = updateDto.Name;
        existPermission.Description = updateDto.Description;
        existPermission.UpdatedAt = DateTime.UtcNow;
        _dbContext.Permissions.Update(existPermission);

        await _dbContext.SaveChangesAsync();
        return true;
    }

    public async Task<bool> DeletePermissionAsync(int id)
    {
        var permissionToDelete = await _dbContext.Permissions.FindAsync(id);
        if (permissionToDelete == null)
        {
            return false;
        }

        _dbContext.Permissions.Remove(permissionToDelete);
        await _dbContext.SaveChangesAsync();
        return true;
    }
}